import { EventStreamContentType, fetchEventSource } from '@microsoft/fetch-event-source';
import { message } from 'antd';
import { useCallback, useEffect, useMemo ,useRef} from 'react';
import { getProcess_report, checkType, comment ,webJump,dataAnalysis} from '@/client/api/request';
import i18n from '@/app/i18n';
/* import EventSource from 'event-source-polyfill'; */
type Props = {
  queryAgentURL?: string;
};

type ChatParams = {
  chatId: string;
  data?: Record<string, any>;
  onMessage: (message: string) => void;
  onClose?: () => void;
  onDone?: () => void;
  onError?: (content: string, error?: Error) => void;
};

const useChat = ({ queryAgentURL = '/api/v1/chat/completions' }: Props) => {
  let ctrl1 = useRef<AbortController>();
  let ctrl2 = useRef<AbortController>();
  let ctrl3 = useRef<AbortController>();
  let ctrl4 = useRef<AbortController>();
  let ctrl5 = useRef<AbortController>();
  let tempMessage = '';
  const chat = useCallback(
    async ({ data, chatId, onMessage, onClose, onDone, onError }: ChatParams) => {
      ctrl1.current = new AbortController();
      ctrl2.current = new AbortController();
      ctrl3.current = new AbortController();
      ctrl4.current = new AbortController();
      ctrl5.current = new AbortController();
      
      checkType({ content: data?.user_input },{
        signal: ctrl3.current.signal,
      }).then(async (res) => {
        if(res.data.code==200){
          
        }
        const checkTypeRes = res.data.type;
        
        tempMessage = '';
        if (checkTypeRes == '数据分析') {
          // if (!data?.user_input && !data?.doc_id) {
          //   message.warning(i18n.t('NoContextTip'));
          //   return;
          // }

          // const parmas = {
          //   ...data,
          //   conv_uid: chatId,
          // };
          // if (!parmas.conv_uid) {
          //   message.error('conv_uid 不存在，请刷新后重试');
          //   return;
          // }
          const parmas = {
            content:data?.user_input
          }
          // try {
          //   await fetchEventSource(`http://localhost:13601/api/v1/chat_with_sql`, {
          //     method: 'POST',
          //     headers: {
          //       'Content-Type': 'application/json',
          //     },
          //     body: JSON.stringify(parmas),
          //     signal: ctrl2.current.signal,
          //     openWhenHidden: true,
          //     async onopen(response) {
          //       if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
          //         return;
          //       }
          //     },
          //     onclose() {
          //       //ctrl2.current.abort();
          //       //onClose?.();
          //     },
          //     onerror(err) {
          //       ctrl2.current.abort();
          //       onClose?.();
          //       throw new Error(err);
          //     },
          //     onmessage: (event) => {
                
          //       //const message = event.data?.replaceAll('\\n', '\n');
          //       /* const message ='www' */
                
          //       const message = JSON.parse(event.data);
          //       Object.keys(message).map((key)=>{
          //         debugger
          //         if(key=="sql_code"){
          //           onMessage("了展示最新季度各个行业门类的新增企业数量，我们需要从'industry_category'表中选出最新季度的数据，并按照'category'（行业门类名称）分组，然后展示每个行业门类的'added_num'（新增企业数量）。首先，我们需要确定最新季度，这可以通过选择'statistical_period'（统计周期）的最大值来实现。然后，我们根据这个最新的统计周期，查询对应的新增企业数量。这个查询结果适合使用饼图展示，因为它可以很好地展示各个行业门类新增企业数量的比例分布")
          //           const chart = '<chart-view' + 'sql&quot;: &quot;'+message[key]+'>';
          //           onMessage?.('<chart-view content="{&quot;type&quot;: &quot;response_pie_chart&quot;, &quot;sql&quot;: &quot;SELECT category, added_num FROM industry_category WHERE statistical_period = (SELECT MAX(statistical_period) FROM industry_category) ORDER BY added_num DESC LIMIT 50&quot;, &quot;data&quot;: [{&quot;category&quot;: &quot;批发和零售业&quot;, &quot;added_num&quot;: 122918}, {&quot;category&quot;: &quot;租赁和商务服务业&quot;, &quot;added_num&quot;: 48703}, {&quot;category&quot;: &quot;科学研究和技术服务业&quot;, &quot;added_num&quot;: 44106}, {&quot;category&quot;: &quot;制造业&quot;, &quot;added_num&quot;: 24478}, {&quot;category&quot;: &quot;信息传输、软件和信息技术服务业&quot;, &quot;added_num&quot;: 24083}, {&quot;category&quot;: &quot;建筑业&quot;, &quot;added_num&quot;: 13987}, {&quot;category&quot;: &quot;文化、体育和娱乐业&quot;, &quot;added_num&quot;: 10509}, {&quot;category&quot;: &quot;住宿和餐饮业&quot;, &quot;added_num&quot;: 8539}, {&quot;category&quot;: &quot;居民服务、修理和其他服务业&quot;, &quot;added_num&quot;: 6943}, {&quot;category&quot;: &quot;交通运输、仓储和邮政业&quot;, &quot;added_num&quot;: 5821}, {&quot;category&quot;: &quot;房地产业&quot;, &quot;added_num&quot;: 5805}, {&quot;category&quot;: &quot;农、林、牧、渔业&quot;, &quot;added_num&quot;: 3613}, {&quot;category&quot;: &quot;卫生和社会工作&quot;, &quot;added_num&quot;: 2523}, {&quot;category&quot;: &quot;电力、热力、燃气及水生产和供应业&quot;, &quot;added_num&quot;: 1147}, {&quot;category&quot;: &quot;教育&quot;, &quot;added_num&quot;: 1012}, {&quot;category&quot;: &quot;水利、环境和公共设施管理业&quot;, &quot;added_num&quot;: 953}, {&quot;category&quot;: &quot;金融业&quot;, &quot;added_num&quot;: 666}, {&quot;category&quot;: &quot;公共管理、社会保障和社会组织&quot;, &quot;added_num&quot;: 376}, {&quot;category&quot;: &quot;采矿业&quot;, &quot;added_num&quot;: 48}, {&quot;category&quot;: &quot;国际组织&quot;, &quot;added_num&quot;: 0}]}" />'||'');
          //         }
                  
          //       })
               
                
          //       console.log(event.data,'event.data');
          //       debugger
          //     },
          //   });
          // } catch (err) {
          //   ctrl2.current.abort();
          //   onClose?.();
          //   onError?.('Sorry, We meet some error, please try agin later.', err as Error);
          // }
          dataAnalysis(parmas,{
            signal: ctrl2.current.signal,
            timeout:60000
          }).then((res:any)=>{
            onClose?.();
            //console.log(res.data.replaceAll('\\n', '\n').replace(/\n/g, ''),"99999999999");
            console.log(typeof res.data,'eeeeee')
            const message  = res.data.replaceAll('data:','')
            const data = message.split('<chart-view')[0];
            const iframeDom = document.getElementById('numberPerson') as HTMLIFrameElement;
            iframeDom?.contentWindow?.postMessage(
              { text: data, eventType: 'message' },
              process.env.NEXT_PUBLIC_HUMAN_BASE_URL,
            );
            iframeDom?.contentWindow?.postMessage(
              { text: '', eventType: 'message_end' },
              process.env.NEXT_PUBLIC_HUMAN_BASE_URL,
            );
            let chart = '<chart-view' + message.split('<chart-view')[1].replaceAll('\\n', '\n').replace(/\n/g, '');
            console.log('charts',chart)
            //onMessage("了展示最新季度各个行业门类的新增企业数量，我们需要从'industry_category'表中选出最新季度的数据，并按照'category'（行业门类名称）分组，然后展示每个行业门类的'added_num'（新增企业数量）。首先，我们需要确定最新季度，这可以通过选择'statistical_period'（统计周期）的最大值来实现。然后，我们根据这个最新的统计周期，查询对应的新增企业数量。这个查询结果适合使用饼图展示，因为它可以很好地展示各个行业门类新增企业数量的比例分布")
            //onMessage?.('<chart-view content="{&quot;type&quot;: &quot;response_pie_chart&quot;, &quot;sql&quot;: &quot;SELECT category, added_num FROM industry_category WHERE statistical_period = (SELECT MAX(statistical_period) FROM industry_category) ORDER BY added_num DESC LIMIT 50&quot;, &quot;data&quot;: [{&quot;category&quot;: &quot;批发和零售业&quot;, &quot;added_num&quot;: 122918}, {&quot;category&quot;: &quot;租赁和商务服务业&quot;, &quot;added_num&quot;: 48703}, {&quot;category&quot;: &quot;科学研究和技术服务业&quot;, &quot;added_num&quot;: 44106}, {&quot;category&quot;: &quot;制造业&quot;, &quot;added_num&quot;: 24478}, {&quot;category&quot;: &quot;信息传输、软件和信息技术服务业&quot;, &quot;added_num&quot;: 24083}, {&quot;category&quot;: &quot;建筑业&quot;, &quot;added_num&quot;: 13987}, {&quot;category&quot;: &quot;文化、体育和娱乐业&quot;, &quot;added_num&quot;: 10509}, {&quot;category&quot;: &quot;住宿和餐饮业&quot;, &quot;added_num&quot;: 8539}, {&quot;category&quot;: &quot;居民服务、修理和其他服务业&quot;, &quot;added_num&quot;: 6943}, {&quot;category&quot;: &quot;交通运输、仓储和邮政业&quot;, &quot;added_num&quot;: 5821}, {&quot;category&quot;: &quot;房地产业&quot;, &quot;added_num&quot;: 5805}, {&quot;category&quot;: &quot;农、林、牧、渔业&quot;, &quot;added_num&quot;: 3613}, {&quot;category&quot;: &quot;卫生和社会工作&quot;, &quot;added_num&quot;: 2523}, {&quot;category&quot;: &quot;电力、热力、燃气及水生产和供应业&quot;, &quot;added_num&quot;: 1147}, {&quot;category&quot;: &quot;教育&quot;, &quot;added_num&quot;: 1012}, {&quot;category&quot;: &quot;水利、环境和公共设施管理业&quot;, &quot;added_num&quot;: 953}, {&quot;category&quot;: &quot;金融业&quot;, &quot;added_num&quot;: 666}, {&quot;category&quot;: &quot;公共管理、社会保障和社会组织&quot;, &quot;added_num&quot;: 376}, {&quot;category&quot;: &quot;采矿业&quot;, &quot;added_num&quot;: 48}, {&quot;category&quot;: &quot;国际组织&quot;, &quot;added_num&quot;: 0}]}" />'||'');
            onMessage?.(data||'')
            onMessage?.(chart || '');
          })
        } else if (checkTypeRes == '基本对话') {
          const commentData = {
            "inputs": {},
            "query": data?.user_input,
            "response_mode": "streaming",
            "conversation_id": '',
            "parent_message_id":null,
            "user": "abc-123",
            "files": []
          }
          try {
            await fetchEventSource(`http://localhost:20080/v1/chat-messages`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
                "Authorization": "Bearer app-6bFzmUAzaOTfhjIlsMzGlpAY"
              },
              body: JSON.stringify(commentData),
              signal: ctrl1.current.signal,
              openWhenHidden: true,
              async onopen(response) {
                if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
                  return;
                }
              },
              onclose() {
                ctrl1.current!.abort();
                onClose?.();
              },
              onerror(err) {
                ctrl1.current.abort();
                throw new Error(err);
              },
              onmessage: (event) => {
                /* const message = event.data?.replaceAll('\\n', '\n'); */
                /* const message ='www' */
                let data = event.data;
                const iframeDom = document.getElementById('numberPerson') as HTMLIFrameElement;
                if(typeof data == "string"&&data!=""){
                  data = JSON.parse(data);
                  if(data.event=="message_end"){
                    iframeDom?.contentWindow?.postMessage(
                      { text: '', eventType: 'message_end' },
                      process.env.NEXT_PUBLIC_HUMAN_BASE_URL,
                    );
                  }
                  console.log(process.env)
                  if(data.event !=="message_replace"){
                    console.log(data.answer,'eventMessage')
                    onMessage?.(data.answer || '');
                   
                    iframeDom?.contentWindow?.postMessage(
                      { text: data.answer, eventType: 'message' },
                      process.env.NEXT_PUBLIC_HUMAN_BASE_URL,
                    );
                  }
                  
                }
                
                // debugger
                // const finishReason = JSON.parse(event.data).choices[0].finishReason;
                // const finishContent = JSON.parse(event.data).choices[0].delta.content;
                // onMessage?.(finishContent || '');
                // tempMessage += finishContent || '';
                
                
              },
            });
          } catch (err) {
            debugger
            ctrl1.current.abort();
            onError?.('Sorry, We meet some error, please try agin later.', err as Error);
          }

          /* console.log(checkTypeRes.data);
          const commentRes = await comment(commentData);
          let finishReason = true; */

          /* while (finishReason) {} */
          /*  let dataCommentRes = JSON.parse(commentRes); */
        }else if(checkTypeRes=='网页跳转'){
          webJump({content:data?.user_input},{
            signal: ctrl5.current.signal,
          }).then(async (res:any)=>{
            onClose?.();
            if(res.data.code==200){
              // const iframeDom = document.getElementById('mapIframe') as HTMLIFrameElement;
              // iframeDom?.contentWindow?.postMessage(
              //   { text: res.data.url, eventType: 'jump' },
              //   process.env.NEXT_PUBLIC_DAPING_BASE_URL,
              // );
              const iframeDom = document.getElementById('numberPerson') as HTMLIFrameElement;
              window.parent.postMessage({ url: res.data.url, eventType: 'jump' },process.env.NEXT_PUBLIC_DAPING_BASE_URL)
              iframeDom?.contentWindow?.postMessage(
                { text: '好的，已为你打开对应页面', eventType: 'message' },
                process.env.NEXT_PUBLIC_HUMAN_BASE_URL,
              );
              iframeDom?.contentWindow?.postMessage(
                { text: '', eventType: 'message_end' },
                process.env.NEXT_PUBLIC_HUMAN_BASE_URL,
              );
              
              onMessage?.('好的，已为你打开对应页面');
            }
            console.log(res,'res111111111')
          })
        }
          console.log('res',res)
      }).catch((error)=>{
        console.log(error)
      });
      
    },
    [queryAgentURL],
  );
  // 取消请求
  const cancelRequest = ()=>{
    if(ctrl1.current&&ctrl2.current&&ctrl3.current&&ctrl4.current&&ctrl5.current){
      console.log('取消请求')
      console.log('ctrl1',ctrl1)
      console.log('ctrl2',ctrl2)
      try{
        ctrl1.current.abort();
        ctrl2.current.abort();
        ctrl3.current.abort();
        ctrl4.current.abort();
        ctrl5.current.abort();
      }catch(error){
        console.log(error)
      }
      
    }
   
  }
  useEffect(() => {
    return () => {
      cancelRequest()
    };
  }, []);

  return {cancelRequest,chat};
};

export default useChat;
